package cn.powertime.evaluation.facade.impl;

import cn.powertime.evaluation.file.storage.FileInfo;
import cn.powertime.evaluation.shiro.ShiroUtils;
import cn.powertime.evaluation.annotation.Facade;
import cn.powertime.evaluation.entity.SysFile;
import cn.powertime.evaluation.facade.SysFileFacade;
import cn.powertime.evaluation.service.SysFileService;
import cn.powertime.evaluation.util.FileUtil_;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.google.common.collect.ImmutableMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.Map;

/**
 * <p>
 * 文件信息表 服务类
 * </p>
 *
 * @author ZYW
 * @since 2019-09-02
 */
@Facade
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public class SysFileFacadeImpl implements SysFileFacade {
    @Autowired
    private SysFileService sysFileService;

    @Override
    public Map<String,String> save(FileInfo fileInfo) {
        SysFile sysFile = new SysFile();

        BeanUtils.copyProperties(fileInfo,sysFile);

        sysFile.setId(IdWorker.getId());
//        String username = ShiroUtils.getUserInfo().getUsername();
        sysFile.setCreateUser("zx");
        sysFile.setUpdateUser("zx");
        boolean result = sysFileService.save(sysFile);
        if (result) {
            return ImmutableMap.of("id", String.valueOf(sysFile.getId()), "type", fileInfo.getExt());
        }
        return null;
    }


    public SysFile getById(String id) {
        return sysFileService.getById(id);
    }



    public boolean trueDeletion(String fileId){
        SysFile sysFile  = getById(fileId);

        FileUtil_ fileUtil_ = new FileUtil_();

        if(sysFile!=null){

            String filePath = sysFile.getPath()+ File.separator+sysFile.getName();

            File file = new File(filePath);

            if(file.exists()){
                return fileUtil_.delFile(file);
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

}
